package com.suray.wcs.service.config.resolver;

import com.alibaba.fastjson.JSON;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.ParamConfig;
import com.suray.wcs.res.msgparse.ByteBeanUtil;
import com.suray.wcs.res.msgparse.HeartBaseResult;
import com.suray.wcs.service.manager.AsyncManager;
import com.suray.wcs.service.manager.factory.AsyncFactory;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.message.RgvLifeRecMessage;
import com.suray.wcs.service.system.entity.InterfaceLogRvg;
import com.suray.wcs.service.system.entity.RgvHeartLogDB;

import java.util.*;

public class RgvLogRecorder {
    private static Map<String, Integer> recordMap = new HashMap<>();

    public static void recordRgvHearLog(Object data, String deviceName, long startTime, long endTime) {
        Integer count = recordMap.get(deviceName);

        if (count == null) {
            count = 0;
        }

        if (count < (ParamConfig.rgvLogRecordTime - 1)) {
            recordMap.put(deviceName, ++count);
            return;
        }

        recordMap.put(deviceName, 0);
        try {
            recordRgvHeart(data, deviceName, startTime, endTime);
        } catch (Exception e) {
            LoggerUtil.warn(deviceName + " 心跳日志记录失败!", RgvLogRecorder.class);
        }
    }

    private static void recordRgvHeart(Object recData, String deviceName, long startTime, long endTime) {
        if (recData instanceof byte[]) {
            byte[] data = (byte[]) recData;
            RgvHeartLogDB rgvHeartLogdb = new RgvHeartLogDB();
            rgvHeartLogdb.setDeviceName(deviceName);

            rgvHeartLogdb.setSendTime(new Date(startTime));
            rgvHeartLogdb.setReceTime(new Date(endTime));
            rgvHeartLogdb.setUseTime(endTime - startTime);

            HeartBaseResult d = (HeartBaseResult) ByteBeanUtil.parseByte(data);
            rgvHeartLogdb.setTaskNo(d.getTaskNo());
            rgvHeartLogdb.setTaskType(d.getTaskType());
            rgvHeartLogdb.setTaskResult(d.getTaskResult());
            rgvHeartLogdb.setRgvLocation("(" + d.getX() + "," + d.getY() + "," + d.getZ() + ")");
            rgvHeartLogdb.setPalletStatus(d.getPalletStatus());
            rgvHeartLogdb.setRgvCurrentSegment(d.getCurentSegment());
            rgvHeartLogdb.setSegmentEndLocation("(" + d.getX() + "," + d.getY() + "," + d.getZ() + ")");
            rgvHeartLogdb.setCurBarcode(String.valueOf(d.getCurBarcode()));
            rgvHeartLogdb.setRgvStatus(d.getRgvStatus() != null ? d.getRgvStatus() : 255);
            rgvHeartLogdb.setReserveStatus(d.getReserveStatus());
            rgvHeartLogdb.setDriveDirection(d.getDriveDirection());
            rgvHeartLogdb.setElectric(d.getBattery());
            rgvHeartLogdb.setCmdNo(d.getCmdNo());
            rgvHeartLogdb.setCmdResult(d.getCmdResult());
            rgvHeartLogdb.setCmdExecuteResult(d.getCmdExecuteResult());
            rgvHeartLogdb.setCmdExecuteResultParam(d.getCmdExecuteResultParam());
            // 日志记录保存到表
            AsyncManager.me().execute(AsyncFactory.recordRgvHeatLog(rgvHeartLogdb));
        } else if (recData instanceof RgvLifeRecMessage) {
            RgvLifeRecMessage recMessage = (RgvLifeRecMessage) recData;
            RgvHeartLogDB rgvHeartLogdb = new RgvHeartLogDB();
            rgvHeartLogdb.setDeviceName(deviceName);

            rgvHeartLogdb.setSendTime(new Date(startTime));
            rgvHeartLogdb.setReceTime(new Date(endTime));
            rgvHeartLogdb.setUseTime(endTime - startTime);

            rgvHeartLogdb.setTaskNo(recMessage.getCmdNo());
            rgvHeartLogdb.setTaskType(recMessage.getCmdType());
            rgvHeartLogdb.setTaskResult(recMessage.getResult());
            rgvHeartLogdb.setRgvLocation("(" + recMessage.getX() + "," + recMessage.getY() + "," + recMessage.getZ() + ")");
            rgvHeartLogdb.setPalletStatus(recMessage.getPalletStatus());
            rgvHeartLogdb.setRgvCurrentSegment(recMessage.getCurrentSegment());
            rgvHeartLogdb.setSegmentEndLocation("(" + recMessage.getX() + "," + recMessage.getY() + "," + recMessage.getZ() + ")");
            rgvHeartLogdb.setCurBarcode(String.valueOf(recMessage.getCurBarcode()));
            rgvHeartLogdb.setRgvStatus(recMessage.getRgvStatus());
            rgvHeartLogdb.setReserveStatus(recMessage.getReserveStatus());
            rgvHeartLogdb.setDriveDirection(recMessage.getDriveDirection());
            rgvHeartLogdb.setElectric(recMessage.getBattery());
            AsyncManager.me().execute(AsyncFactory.recordRgvHeatLog(rgvHeartLogdb));
        }
    }

    public static void recordAction(String des, String deviceName, Object[] args, Object returnData, long startTime) {
        try {
            InterfaceLogRvg interfaceLogRvg = new InterfaceLogRvg();
            interfaceLogRvg.setMessage(des);
            interfaceLogRvg.setDeviceName(deviceName);
            // 方法传入参数为byte[]的处理
            if (args != null && args.length == 1 && args[0] instanceof byte[]) {
                interfaceLogRvg.setRgvParamsIn(Arrays.toString((byte[]) args[0]));
            } else { // 方法传入参数为非byte[]的处理

                interfaceLogRvg.setTackId(args.length != 0 ? (Integer) args[0] : null);
                List<Object> argList = Arrays.asList(args);
                List<Object> newArgs = new ArrayList<>(argList);
                newArgs.remove(0);
                interfaceLogRvg.setRgvParamsIn(newArgs.size() == 0 ? "无" : newArgs.toString());
            }

            long endTime = System.currentTimeMillis();
            interfaceLogRvg.setOperateTime(new Date(startTime));
            interfaceLogRvg.setUseTime(endTime - startTime);
            interfaceLogRvg.setState(0);

            // 返回对象为byte[]时的处理
            if (returnData instanceof byte[]) {
                interfaceLogRvg.setBacktrack(Arrays.toString((byte[]) returnData));
            } else { // 返回对象b为非byte[]时的处理
                interfaceLogRvg.setBacktrack(JSON.toJSONString(returnData == null ? "无" : returnData));
            }
            // 日志记录保存到表
            AsyncManager.me().execute(AsyncFactory.recordRgvActionLog(interfaceLogRvg));
        } catch (Exception e) {
            LoggerUtil.warn(deviceName + " 动作交互日志记录失败!", RgvLogRecorder.class);
        }
    }
}
